// import QtQuick 1.0 // to target S60 5th Edition or Maemo 5
import QtQuick 1.1
import QMLAdb 1.0
import QMLFile 1.0
import "Components"
import "./js/ThemeInfo.js" as ThemeInfo

GroupBox {
    id: _root
    width: _area.width + 20
    height: _area.height + _area.anchors.topMargin + 5

    text: "  デバイス  "
    textBkSource: "images/background.png"
    borderColor: "#888888"
    borderBkColor: "#00000000"
    radius: 5
    color: "#dddddd"

    //adb設定へのエイリアス
    property alias adbPath: _adb.adbPath

    //デプロイ用の設定
    property string localPath: ""
    property string remotePath: ""
    property string remotePathTemp: ""

    //デプロイ中のプログレス用
    signal startProgress(double max)
    signal updateProgress(double value, string message)
    signal endProgress()

    //ダイアログ表示要求
    signal showDialog(string title, string message, variant myelm, int id)

    //デバイスリストを更新
    function updateDeviceList(){
        _deviceList.clear();
        _adb.postAdbDevices();
    }

    //ダイアログ呼び出し時のコールバック
    function callbackMessageDialog(id){
        startDeploy();
    }

    //転送開始
    function startDeploy(){
        if(_adb.checkSetting() === true && _adb.checkDevice() === true){
            var i=0;
            var items = [
                        "PATH_LAUNCHER"
                        , "PATH_LOCKSCREEN"
                        , "PATH_NAVIKEY_BACK"
                        , "PATH_NAVIKEY_EXPAND"
                        , "PATH_NAVIKEY_HOME"
                        , "PATH_NAVIKEY_MENU"
                        , "PATH_NAVIKEY_RECENT"
                        , "PATH_NAVIKEY_BACK_LAND"
                        , "PATH_NAVIKEY_EXPAND_LAND"
                        , "PATH_NAVIKEY_HOME_LAND"
                        , "PATH_NAVIKEY_MENU_LAND"
                        , "PATH_NAVIKEY_RECENT_LAND"
                        , "PATH_NOTIFICATION_ITEM_NORMAL"
                        , "PATH_NOTIFICATION_ITEM_PRESSED"
                        , "PATH_NOTIFICATION_TRACKINGBG"
                        , "PATH_SCREENSHOT"
                        , "PATH_WALLPAPER"
                        , "PATH_RECENT_FRAME"
                        , "PATH_STATUSBAR_BAR_BACKGROUND"
                        //ちょっとまって
                        , "PATH_SIMEJI_JCROM_PORT"
                        , "PATH_SIMEJI_JCROM_LAND"
                        //ココから下は転送のみ
                        , "PATH_SOUNDS_EFFECT_CARDOCK"
                        , "PATH_SOUNDS_EFFECT_DOCK"
                        , "PATH_SOUNDS_EFFECT_EFFECT_TICK"
                        , "PATH_SOUNDS_EFFECT_KEYPRESS_DELETE"
                        , "PATH_SOUNDS_EFFECT_KEYPRESS_RETURN"
                        , "PATH_SOUNDS_EFFECT_KEYPRESS_SPACEBAR"
                        , "PATH_SOUNDS_EFFECT_KEYPRESS_STANDARD"
                        , "PATH_SOUNDS_EFFECT_LOCK"
                        , "PATH_SOUNDS_EFFECT_LOWBATTERY"
                        , "PATH_SOUNDS_EFFECT_UNCARDOCK"
                        , "PATH_SOUNDS_EFFECT_UNDOCK"
                        , "PATH_SOUNDS_EFFECT_UNLOCK"
                        , "PATH_DOT_NOMEDIA"
                        ];
            ThemeInfo.deploy_file_list = [];
            for(i=0; i<items.length; i++){
                ThemeInfo.deploy_file_list.push(ThemeInfo.ITEM_PATH[items[i]]);
            }
            //起動アニメは探す
            var animeList = _file.getEntryList(localPath + ThemeInfo.ITEM_PATH["PATH_BOOTANIME"]
                                               , QMLFile.Files, ["bootanimation*.zip"]);
            for(i=0; i<animeList.length; i++){
                ThemeInfo.deploy_file_list.push(ThemeInfo.ITEM_PATH["PATH_BOOTANIME"] + animeList[i]);
            }
            //開始のシグナル
            _root.startProgress(ThemeInfo.deploy_file_list.length);

            //デプロイ開始
            deployFiles();
        }
    }

    //pushする
    function deployFiles(){
        if(ThemeInfo.deploy_file_list.length > 0){
            var value = ThemeInfo.deploy_file_list.length;
            var file = ThemeInfo.deploy_file_list.shift();

            //途中のシグナル
            updateProgress(value, file);

            //転送（まずはテンポラリへ）
            if(_adb.postAdbPush(localPath + file, remotePathTemp + "/" + file) !== true){
                console.debug("deploy error");
            }
        }else{
            //転送終了したらフォルダの入れ替え
            //転送したテンポラリが無かったらリネームはしない。
            var cmd = "ls " + remotePathTemp + " &&"
                    + "rm -r " + remotePath + ";"
                    + "mv " + remotePathTemp + " " + remotePath + ";"
                    + "exit\n";
            console.debug(cmd);
            _adb.postShellCommand(cmd);

            endProgress();
        }
    }


    QMLAdb{
        id: _adb
        adbPath: ""
        deviceName: ""

        function checkSetting(){
            var ret = false;
            if(adbPath.length > 0){
                ret = true;
            }else{
                _toast.show("adbのパスを設定してください。");
            }
            return ret;
        }
        function checkDevice(){
            var ret = false;
            if(deviceName.length > 0){
                ret = true;
            }else{
                _toast.show("デバイス情報を更新してください。");
            }
            return ret;
        }


        onFinished:{
            var temp;
            var i;
            console.debug("adb finish:c=" + exitCode + ",m=" + mode);

            switch(mode){
            case QMLAdb.Push:
                for(i=0;i<result.length;i++){
                    if(result[i] === "fail"){
                        console.debug("  adb push ng");
                    }
                }
                deployFiles();
                break;

            case QMLAdb.Pull:
                break;
            case QMLAdb.Devices:
                for(i=0;i<result.length;i++){
                    temp = result[i].split("\t");
                    if(temp.length !== 2){
                    }else if(temp[1] !== "device"){
                    }else{
                        _deviceList.append(temp[0]);
                    }
                }
                if(_deviceList.count > 0){
                    _adb.deviceName = _deviceList.get(0)._title;
                    _deviceList.setCurrentIndex(0);
                }

                break;

            case QMLAdb.ShellCommand:
                //シェルコマンド

                //終了のシグナル
                endProgress();
                break;

            default:
                break;
            }

            for(i=0;i<result.length;i++){
                console.debug("  " + i + ":" + result[i]);
            }
        }
        onAdbPathChanged:{
            console.debug("change adb path:" + adbPath);
        }
        onDeviceNameChanged:{
            console.debug("change deviceName:" + deviceName);
        }
    }


    Column{
        id: _area
        anchors.top: parent.top
        anchors.topMargin: parent.textHeight + 5
        anchors.left: parent.left
        anchors.leftMargin: 10

        spacing: 5

        Button{
            text: "  転送...  "
            enabled: (_root.adbPath.length > 0) && ( _adb.deviceName.length > 0)
            onClicked: {
                showDialog("転送開始"
                           , "選択しているテーマを転送します。\n/// 注意 ///\n転送先に同名のテーマが既にある場合一度削除されます。"
                           , _root
                           , 1);
//                startDeploy();
            }
        }

        Row{
            spacing: 5
            Button{
                text: "  更新  "
                enabled: (_root.adbPath.length > 0)
                onClicked: {
                    if(_adb.checkSetting() === true){
                        _root.updateDeviceList();
                    }
                }
            }

            Button{
                text: "adbパス設定"
                onClicked: {
                    var file = _file.getOpenFileName("adb選択", "", "");
                    if(file.length > 0){
                        _adb.adbPath = file;
                    }
                }
            }
        }

//        Button{
//            text: "テスト"
//            onClicked: {
//                if(_adb.checkDevice() === true){

////                    _adb.postShellCommand("mkdir /sdcard/mytheme/てすてす;exit\n");
////                    _adb.postShellCommand("ls /sdcard/mytheme;pwd;exit\n");
//                    _adb.postShellCommand("rm -r /sdcard/mytheme/Shirakawa;mv /sdcard/mytheme/JTS_TEMP /sdcard/mytheme/Shirakawa;exit\n");
//                }
//            }
//        }

        ListViewSimple{
            id: _deviceList
            width: 150
            height: 140
            onClicked: {
                _adb.deviceName = title;
            }
        }

        Button{
            text: " 再起動 "
            enabled: (_root.adbPath.length > 0) && ( _adb.deviceName.length > 0)
            onClicked: {
                if(_adb.checkDevice() === true){
                    _adb.postAdbReboot(QMLAdb.RebootNormal);
                }
            }
        }

    }

}
